package com.sgcc.auth.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.sgcc.auth.form.LoginBody;
import com.sgcc.auth.service.SysLoginService;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.utils.HttpClient;
import com.sgcc.common.core.utils.StringUtils;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.system.api.model.LoginUser;

import net.sf.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * token 控制
 * 
 * @author sgcc
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;
    
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        String username="";
        try {
            username=URLDecoder.decode(form.getUsername(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 用户登录
        LoginUser userInfo = sysLoginService.login(username, form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }
    
    @PostMapping("isc")
    public R<?> loginIsc(@RequestBody String obj,HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws Exception
    {
    	
    	JSONObject isc =doIsc(obj);
		if(null!=isc) {
			String iscUserSourceId=isc.getString("iscUserSourceId");//账号
//			String iscAdCode=isc.getString("iscAdCode");//账号
//			String baseOrgId=isc.getString("baseOrgId");//组织ID
			String iscUserId=isc.getString("iscUserId");//ID
//			String passWord=isc.getString("passWord");//密码
	        // 用户登录
	        LoginUser userInfo = sysLoginService.loginISC(iscUserSourceId);
            userInfo.setIscUserid(iscUserId);
	        // 获取登录token
	        return R.ok(tokenService.createToken(userInfo));
		}else {
			return R.fail("登录失败~");
		}
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
    @Value("${isc.url}")
    private String url;
    @Value("${isc.baseUrl}")
    private String baseUrl;
    public JSONObject doIsc(String obj)  
			throws Exception {  
		//https://myproject.picp.vip/isc_sso/serviceValidate?service=http://172.16.26.166:8080/yypc/loginIsc&ticket=ST-81-schVCCTJfydepxKDZoZz-uapsso.example.org
//		String iscurl="https://myproject.picp.vip/isc_sso/serviceValidate";
		String iscurl=url+"/isc_sso/serviceValidate";
		String ticket=JSONObject.fromObject(obj).getString("ticket");
		String param="service="+baseUrl+"&ticket="+ticket;
		try {
			HttpClient hc=new HttpClient();
			String str=hc.get(iscurl+"?"+param);
			str=str.replaceAll("<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>", "");
			str=str.replaceAll("<cas:authenticationSuccess>", "");
			str=str.replaceAll("<cas:user>", "");
			str=str.replaceAll("</cas:user>", "");
			str=str.replaceAll("</cas:authenticationSuccess>", "");
			str=str.replaceAll("</cas:serviceResponse>", "");
			
			str=java.net.URLDecoder.decode(str, "utf-8");
			JSONObject res=JSONObject.fromObject(str);
			return res;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}  	
}
